package forecasting.converter;

import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;

public class DiscreteValue extends FeatureType {
	private final Set<String> values;
	
	public DiscreteValue(String name) {
		super(name);
		this.values = new HashSet<String>();
	}
	
	public void addValue(String val) {
		values.add(val);
	}
	
	public static String replaceQuotes(String str) {
		if(str.contains("\"")) {
			StringTokenizer tok = new StringTokenizer(str, "\"");
			StringBuilder build = new StringBuilder();
			while(tok.hasMoreTokens())
				build.append(tok.nextToken() + "\\\"");
			return build.toString();
		}
		return str;
	}
	
	public static boolean hasSpaces(String val) {
		for(int i = 0; i < val.length(); i++)
			if(val.charAt(i) == ' ')
				return true;
		return false;
	}
	
	@Override
	public String toString() {
		StringBuilder str = new StringBuilder();
		str.append(" {");
		boolean isFirst = true;
		for(String val: values) {
			// skip empty values
			if (val == null || val.isEmpty()) {
				continue;
			}
			
			// only append a "," if this is not the first column
			if (!isFirst) {
				str.append(", ");
		 	} else {
		 		isFirst = false;
		 	}
		
			// if there are spaces in the string, surround the string with quotes
				str.append("\"" + replaceQuotes(val) + "\"");
			//} else {
				//str.append(replaceQuotes(val));
			//}
		}
		str.append("}");
		//if(hasSpaces(name))
			return super.toString() + "\"" +replaceQuotes(name)  + "\"" + str.toString();
		//else
			//return super.toString() + replaceQuotes(name) + str.toString();
	}
}
